package com.bds.tjj.filter;

import java.util.Calendar;
import java.util.Date;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nutz.dao.impl.NutDao;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.bds.tjj.action.BaseAction;
import com.bds.tjj.model.common.UserSession;

/**
 * Created by guoyu on 2018/1/29.
 */

public class SessionInterceptor extends BaseAction implements HandlerInterceptor {
	private Set<String> writeUrls;

	private NutDao dao;

	public SessionInterceptor(NutDao dao) {
		this.dao = dao;
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		boolean pass = false;

		String path = request.getServletPath();

		UserSession user = getUserSession(request);

		if (user != null) {
			path = path.substring(1, path.length());
			if (!user.getType().equals("admin")) {
				Date startDate = user.getStart_date();
				Calendar cal = Calendar.getInstance();

				cal.setTime(startDate);

				cal.add(Calendar.DATE, user.getDay());

				Date endDate = cal.getTime();

				Date nowDate = new Date();
				if (nowDate.after(endDate)) {

					pass = false;
				} else {
					pass = true;
				}

			} else {
				pass = true;
			}
			if (pass) {
				return true;
			} else {
				String context = request.getContextPath();
				response.sendRedirect(context + "/login.html");
				return false;
			}
		} else {

			// 不需要登录验证
			if (writeUrls != null) {
				for (String url : writeUrls) {
					if (path.matches(url)) {
						pass = true;
					}
				}
			}

			if (pass) {
				return true;
			} else {
				if (pass) {
					return true;
				} else {
					String context = request.getContextPath();
					response.sendRedirect(context + "/login.html");
					return false;
				}

			}
		}

	}

	@Override
	public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,
			ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
			Object o, Exception e) throws Exception {

	}

	public Set<String> getWriteUrls() {
		return writeUrls;
	}

	public void setWriteUrls(Set<String> writeUrls) {
		this.writeUrls = writeUrls;
	}

}
